<template>
  <view class="container">
    <!-- Header Stats -->
    <view class="stats-header">
      <view class="header-title">练习记录</view>
      <view v-if="summaryStats" class="stats-summary">
        <view class="stat-item">
          <text class="stat-value">{{ summaryStats.totalPractices }}</text>
          <text class="stat-label">总练习次数</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ summaryStats.averageAccuracy }}%</text>
          <text class="stat-label">平均正确率</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ summaryStats.bestScore }}</text>
          <text class="stat-label">最高分数</text>
        </view>
      </view>
    </view>

    <!-- Records List -->
    <view v-if="records.length > 0" class="records-container">
      <view
          v-for="(record, index) in records"
          :key="record.id || index"
          class="record-item"
          @tap="viewRecordDetail(record)"
      >
        <view class="record-header">
          <view class="record-type-container">
            <view class="record-type">{{ getTypeName(record.type) }}</view>
            <view class="record-date">{{ formatDate(record.date || record.timestamp) }}</view>
          </view>
          <view :class="getScoreClass(record.score)" class="record-score">
            {{ record.score || 0 }}分
          </view>
        </view>

        <view class="record-details">
          <view class="detail-row">
            <view class="detail-item">
              <text class="detail-value">{{ record.correctCount }}/{{ record.questionCount || record.totalCount || record.totalQuestions }}</text>
              <text class="detail-label">答对题数</text>
            </view>
            <view class="detail-item">
              <text class="detail-value">{{ record.accuracy }}%</text>
              <text class="detail-label">正确率</text>
            </view>
            <view class="detail-item">
              <text class="detail-value">{{ formatTime(record.averageTime || 0) }}</text>
              <text class="detail-label">平均用时</text>
            </view>
          </view>
        </view>

        <view v-if="record.levelName" class="record-level">
          <uni-icons :color="getLevelColor(record.level)" size="16" type="medal"></uni-icons>
          <text>{{ record.levelName }}</text>
        </view>
      </view>
    </view>

    <!-- Empty State -->
    <view v-else class="empty-state">
      <view class="empty-icon">
        <uni-icons color="#ccc" size="60" type="list"></uni-icons>
      </view>
      <view class="empty-text">暂无练习记录</view>
      <button class="start-practice-btn" @tap="startPractice">开始练习</button>
    </view>
  </view>
</template>

<script>
import Storage from '@/utils/storage.js';
import CommonUtils from '@/utils/common.js';

export default {
  data() {
    return {
      records: [],
      summaryStats: null
    }
  },
  // 页面加载时调用
  onLoad() {
    this.loadRecords();
    this.calculateSummaryStats();
  },
  // 页面显示时调用（从其他页面返回时）
  onShow() {
    this.loadRecords();
    this.calculateSummaryStats();
  },
  methods: {
    // 加载所有类型的练习记录
    loadRecords() {
      // 获取各种类型的练习记录
      const speedCalcRecords = Storage.getSpeedCalcRecords() || [];
      const speedCalcChoiceRecords = Storage.get('speed_calc_choice_records', []);
      const speedJudgeRecords = Storage.get('speed_judge_records', []);
      const speedJudgeChoiceRecords = Storage.get('speed_judge_choice_records', []);
      const speedFormulaChoiceRecords = Storage.get('speed_formula_choice_records', []);

      // 为每条记录添加类型标签并标准化字段名称
      const allRecords = [
        ...speedCalcRecords.map(r => ({ ...r, type: 'speed-calc' })),
        ...speedCalcChoiceRecords.map(r => ({ ...r, type: 'speed-calc-choice', correctCount: r.correctCount, questionCount: r.totalCount })),
        ...speedJudgeRecords.map(r => ({ ...r, type: 'speed-judge' })),
        ...speedJudgeChoiceRecords.map(r => ({ ...r, type: 'speed-judge-choice', correctCount: r.correctCount, questionCount: r.totalCount })),
        ...speedFormulaChoiceRecords.map(r => ({ ...r, type: 'speed-formula-choice', correctCount: r.correctCount, questionCount: r.totalCount }))
      ];

      // 按日期排序（最新的在前）
      this.records = allRecords.sort((a, b) => {
        const dateA = new Date(a.date || a.timestamp || 0);
        const dateB = new Date(b.date || b.timestamp || 0);
        return dateB.getTime() - dateA.getTime();
      });
    },

    // 计算汇总统计信息
    calculateSummaryStats() {
      if (this.records.length === 0) {
        this.summaryStats = null;
        return;
      }

      // 总练习次数
      const totalPractices = this.records.length;
      // 筛选有正确率的记录
      const validRecords = this.records.filter(r => r.accuracy);
      // 计算平均正确率
      const averageAccuracy = validRecords.length > 0
        ? Math.round(validRecords.reduce((sum, r) => sum + r.accuracy, 0) / validRecords.length)
        : 0;
      // 获取最高分数
      const bestScore = Math.max(...this.records.map(r => r.score || 0), 0);

      this.summaryStats = {
        totalPractices,
        averageAccuracy,
        bestScore
      };
    },

    // 查看记录详情
    viewRecordDetail(record) {
      const typeName = this.getTypeName(record.type);
      const date = this.formatDate(record.date || record.timestamp);
      const timeInfo = record.totalTime ? `总用时：${this.formatTime(record.totalTime)}` : '';
      
      uni.showModal({
        title: typeName,
        content: `日期：${date}\n分数：${record.score || 0}分\n正确率：${record.accuracy || 0}%\n${timeInfo}`,
        showCancel: false
      });
    },

    // 前往开始练习
    startPractice() {
      uni.navigateTo({
        url: '/pages/speed-calc/settings'
      });
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '未知日期';
      return CommonUtils.formatDate(date);
    },

    // 格式化时间
    formatTime(seconds) {
      return CommonUtils.formatTime(seconds);
    },

    // 根据分数获取样式类名
    getScoreClass(score) {
      if (score >= 200) return 'score-excellent';
      if (score >= 150) return 'score-good';
      if (score >= 100) return 'score-normal';
      return 'score-poor';
    },

    // 根据等级获取颜色
    getLevelColor(level) {
      const colors = {
        'beginner': '#6c757d',
        'intermediate': '#007bff',
        'advanced': '#28a745',
        'expert': '#ffc107',
        'master': '#dc3545'
      };
      return colors[level] || '#6c757d';
    },

    // 获取练习类型名称
    getTypeName(type) {
      const names = {
        'speed-calc': '速算练习',
        'speed-calc-choice': '速算选择',
        'speed-judge': '速判练习',
        'speed-judge-choice': '速判选择',
        'speed-formula-choice': '公式速判'
      };
      return names[type] || '未知类型';
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.stats-header {
  background: linear-gradient(135deg, #67e8f9, #38bdf8);
  padding: 60rpx 40rpx 40rpx;
  color: white;

  .header-title {
    font-size: 40rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .stats-summary {
    display: flex;
    justify-content: space-around;

    .stat-item {
      text-align: center;

      .stat-value {
        display: block;
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
      }

      .stat-label {
        font-size: 24rpx;
        opacity: 0.9;
      }
    }
  }
}

.records-container {
  padding: 30rpx 40rpx;

  .record-item {
    background: white;
    border-radius: 15rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 3rpx 10rpx rgba(0, 0, 0, 0.05);

    .record-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      .record-type-container {
        flex: 1;

        .record-type {
          font-size: 28rpx;
          font-weight: bold;
          color: #007AFF;
          margin-bottom: 5rpx;
        }

        .record-date {
          font-size: 24rpx;
          color: #999;
        }
      }

      .record-date {
        font-size: 26rpx;
        color: #666;
      }

      .record-score {
        font-size: 30rpx;
        font-weight: bold;

        &.score-excellent {
          color: #28a745;
        }

        &.score-good {
          color: #007AFF;
        }

        &.score-normal {
          color: #ffc107;
        }

        &.score-poor {
          color: #dc3545;
        }
      }
    }

    .record-details {
      .detail-row {
        display: flex;
        justify-content: space-around;

        .detail-item {
          text-align: center;

          .detail-value {
            display: block;
            font-size: 28rpx;
            font-weight: bold;
            color: #333;
            margin-bottom: 5rpx;
          }

          .detail-label {
            font-size: 22rpx;
            color: #666;
          }
        }
      }
    }

    .record-level {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 15rpx;
      padding-top: 15rpx;
      border-top: 1rpx solid #f0f0f0;

      text {
        font-size: 24rpx;
        margin-left: 8rpx;
      }
    }
  }
}

.empty-state {
  text-align: center;
  padding: 100rpx 40rpx;

  .empty-icon {
    margin-bottom: 30rpx;
  }

  .empty-text {
    font-size: 32rpx;
    color: #999;
    margin-bottom: 40rpx;
  }

  .start-practice-btn {
    background: linear-gradient(135deg, #67e8f9, #38bdf8);
    color: white;
    border: none;
    border-radius: 25rpx;
    padding: 25rpx 50rpx;
    font-size: 28rpx;
  }
}
</style>